package com.jqsoft.android.facesdk.face;

import android.Manifest;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jqsoft.android.facesdk.FaceSDKManager;
import com.jqsoft.android.facesdk.PeopleBaseInfoBean;
import com.jqsoft.android.facesdk.lib.Base64Util;
import com.jqsoft.android.facesdk.lib.ToolUtil;
import com.jqsoft.launcher.R;
import com.jqsoft.launcher.util.GotoActivityHelper;

import java.io.Serializable;


public class FaceMainActivity extends AppCompatActivity {
    private final String TAG = this.getClass().toString();
    Drawable drawable;
    private static final int REQUEST_CODE_IMAGE_CAMERA = 1;
    private static final int REQUEST_CODE_IMAGE_OP = 2;
    private static final int REQUEST_CODE_OP = 3;
    private PeopleBaseInfoBean mpeopleBasebean;
    private TextView Tusername, usrid, tv_xiangsi;

    private ImageView Registerimage, arcfac;

    private Button btn_start;
    private Uri myuri;

    //private List<SavePhotoBean> savePhotoBeenList = new ArrayList<>();
    Handler mHandler;

    /* (non-Javadoc)
     * @see android.app.Activity#onCreate(android.os.Bundle)
     *
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_facesdk_main);


        Registerimage = (ImageView) findViewById(R.id.arcfac);

        btn_start = (Button) findViewById(R.id.btn_start);

        arcfac = (ImageView) findViewById(R.id.arcfac);

        btn_start.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(FaceMainActivity.this)
                        .setTitle("请选择相机")
                        .setIcon(android.R.drawable.ic_dialog_info)
                        .setItems(new String[]{"后置相机", "前置相机"}, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                startDetector(which);
                            }
                        })
                        .show();
            }
        });

        arcfac.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(FaceMainActivity.this)
                        .setTitle("请选择注册方式")
                        .setIcon(android.R.drawable.ic_dialog_info)
                        .setItems(new String[]{"打开图片", "拍摄照片"}, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case 1:

                                        if (Build.VERSION.SDK_INT >= 23) {
                                            int checkCallPhonePermission = ContextCompat.checkSelfPermission(FaceMainActivity.this, Manifest.permission.CAMERA);
                                            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                                                ActivityCompat.requestPermissions(FaceMainActivity.this, new String[]{Manifest.permission.CAMERA}, 222);
                                                return;
                                            } else {

                                                openCamra();//调用具体方法
                                            }
                                        } else {

                                            openCamra();//调用具体方法
                                        }


                                        break;
                                    case 0:
                                        Intent getImageByalbum = new Intent(Intent.ACTION_GET_CONTENT);
                                        getImageByalbum.addCategory(Intent.CATEGORY_OPENABLE);
                                        getImageByalbum.setType("image/jpeg");
                                        startActivityForResult(getImageByalbum, REQUEST_CODE_IMAGE_OP);
                                        break;
                                    default:
                                        ;
                                }
                            }
                        })
                        .show();
            }
        });

			/*View v = this.findViewById(R.id.arcfac);
            v.setOnClickListener(this);
			v = this.findViewById(R.id.btn_start);
			v.setOnClickListener(this);*/
        Tusername = (TextView) findViewById(R.id.textusername);
        usrid = (TextView) findViewById(R.id.tv_update_card);
        tv_xiangsi = (TextView) findViewById(R.id.tv_xiangsi);
        getdate();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            //就像onActivityResult一样这个地方就是判断你是从哪来的。
            case 222:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                    openCamra();
                } else {
                    // Permission Denied
                    Toast.makeText(FaceMainActivity.this, "请开启拍照权限。", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private void openCamra() {

        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        ContentValues values = new ContentValues(1);
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        //	((DaggerApplication)(FaceMainActivity.this.getApplicationContext())).setCaptureImage(uri);
        myuri = uri;
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, REQUEST_CODE_IMAGE_CAMERA);
    }


    /* (non-Javadoc)
     * @see android.app.Activity#onDestroy()
     */
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //	super.onActivityResult(requestCode, resultCode, data);
        Resources resources = this.getResources();
        Drawable drawable1 = resources.getDrawable(R.mipmap.face);
        if (requestCode == REQUEST_CODE_IMAGE_OP && resultCode == RESULT_OK) {
            Uri mPath = data.getData();
            String file = getPath(mPath);
            Bitmap bmp = ToolUtil.decodeImage(file);
            if (bmp == null || bmp.getWidth() <= 0 || bmp.getHeight() <= 0) {
                Registerimage.setImageDrawable(drawable1);
                Log.e(TAG, "error");
            } else {
                if (FaceSDKManager.getInstance().getFaceRegister()) {
                    Registerimage.setImageDrawable(drawable);
                } else {
                    Registerimage.setImageDrawable(drawable1);
                }
                Log.i(TAG, "bmp [" + bmp.getWidth() + "," + bmp.getHeight());
            }

            drawable = new BitmapDrawable(bmp);


            startRegister(bmp, file);
        } else if (requestCode == REQUEST_CODE_OP) {

            //注册返回时，会得到注册后的图片路径
            Log.i(TAG, "RESULT =" + resultCode);
            if (data == null) {
                Registerimage.setImageDrawable(drawable1);
                return;
            }
            Bundle bundle = data.getExtras();
            String path = bundle.getString("imagePath");


            Log.i(TAG, "path=" + path);
            Bitmap bmp = ToolUtil.decodeImage(path);

            drawable = new BitmapDrawable(bmp);

            if (FaceSDKManager.getInstance().getFaceRegister().equals(true)) {
                Registerimage.setImageDrawable(drawable);
                tv_xiangsi.setText("");

            } else if (FaceSDKManager.getInstance().getFaceRegister().equals(false)) {
                Registerimage.setImageDrawable(drawable1);
                tv_xiangsi.setText("");

            }


        } else if (requestCode == REQUEST_CODE_IMAGE_CAMERA && resultCode == RESULT_OK) {
            //	Uri mPath = ((DaggerApplication)(FaceMainActivity.this.getApplicationContext())).getCaptureImage();

            Uri mPath = myuri;
            String file = getPath(mPath);
            Bitmap bmp = ToolUtil.decodeImage(file);
            drawable = new BitmapDrawable(bmp);

            drawable = new BitmapDrawable(bmp);
            if (FaceSDKManager.getInstance().getFaceRegister().equals(true)) {
                Registerimage.setImageDrawable(drawable);
            } else if (FaceSDKManager.getInstance().getFaceRegister().equals(false)) {

                Registerimage.setImageDrawable(drawable1);
                tv_xiangsi.setText("");
            }

            startRegister(bmp, file);
            Registerimage.setImageDrawable(drawable);
            tv_xiangsi.setText("");


        } else if (requestCode == 5) {
            String change = "";
            if (data == null) {
                change = "000";
            } else {
                change = data.getStringExtra("change01");
            }

            if (change != null) {
                if (change.equals("300")) {

                } else {
                    tv_xiangsi.setText(FaceSDKManager.getInstance().getSimilarity() + "%");
                    final Object obj = getIntent().getSerializableExtra("obj");
                    final String pagetype = getIntent().getStringExtra("pagetype");
                    new AlertDialog.Builder(FaceMainActivity.this)
                            .setTitle("检测成功")
                            .setMessage("相似度为:" + FaceSDKManager.getInstance().getSimilarity() + "%")
                            .setIcon(android.R.drawable.ic_dialog_alert)
                            .setPositiveButton("去执行", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    FaceSDKManager.getInstance().setArcfacesuccess(false);
                                    dialog.dismiss();
                                    GotoActivityHelper.gotoMediaDetailActivity(FaceMainActivity.this, (Serializable) obj, pagetype);
                                    finish();
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            })
                            .show();
                }
            } else {

            }


        }
    }


    /**
     * @param uri
     * @return
     */
    private String getPath(Uri uri) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (DocumentsContract.isDocumentUri(this, uri)) {
                // ExternalStorageProvider
                if (isExternalStorageDocument(uri)) {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];

                    if ("primary".equalsIgnoreCase(type)) {
                        return Environment.getExternalStorageDirectory() + "/" + split[1];
                    }

                    // TODO handle non-primary volumes
                } else if (isDownloadsDocument(uri)) {

                    final String id = DocumentsContract.getDocumentId(uri);
                    final Uri contentUri = ContentUris.withAppendedId(
                            Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                    return getDataColumn(this, contentUri, null, null);
                } else if (isMediaDocument(uri)) {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];

                    Uri contentUri = null;
                    if ("image".equals(type)) {
                        contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    } else if ("video".equals(type)) {
                        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    } else if ("audio".equals(type)) {
                        contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    }

                    final String selection = "_id=?";
                    final String[] selectionArgs = new String[]{
                            split[1]
                    };

                    return getDataColumn(this, contentUri, selection, selectionArgs);
                }
            }
        }
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = this.getContentResolver().query(uri, proj, null, null, null);
        int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        actualimagecursor.moveToFirst();
        String img_path = actualimagecursor.getString(actual_image_column_index);
        String end = img_path.substring(img_path.length() - 4);
        if (0 != end.compareToIgnoreCase(".jpg") && 0 != end.compareToIgnoreCase(".png")) {
            return null;
        }
        return img_path;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param mBitmap
     */
    private void startRegister(Bitmap mBitmap, String file) {
        Intent it = new Intent(FaceMainActivity.this, RegisterActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("imagePath", file);

        it.putExtra("mpeopleBasebean", (Serializable) mpeopleBasebean);
//		it.putExtra("sYear", sYear);
//		it.putExtra("sSignKey", sSignKey);


        it.putExtras(bundle);
        startActivityForResult(it, REQUEST_CODE_OP);
    }

    private void startDetector(int camera) {
        Intent it = new Intent(FaceMainActivity.this, DetecterActivity.class);
        //	mpeopleBasebean = (PeopleBaseInfoBean) this.getIntent().getSerializableExtra("mpeopleBasebean");
        it.putExtra("mpeopleBasebean", (Serializable) mpeopleBasebean);
        it.putExtra("Camera", camera);
        startActivityForResult(it, 5);
    }

    public void getdate() {
        mpeopleBasebean = (PeopleBaseInfoBean) this.getIntent().getSerializableExtra("mpeopleBasebean");
        if (mpeopleBasebean != null) {
            Tusername.setText(mpeopleBasebean.getUserName());
            usrid.setText(mpeopleBasebean.getCardNo());
            if (!TextUtils.isEmpty(mpeopleBasebean.getPhotoUrl())) {
                Bitmap bmp = Base64Util.base64ToBmp(mpeopleBasebean.getPhotoUrl());
                if (null != bmp) {
                    arcfac.setImageBitmap(bmp);
                    arcfac.setEnabled(false);
                }
            }
        }

//		Map<String, String> map = ParametersFactory.getPeopleSignInfo(this, sYear,sSignKey);
//		RequestBody body = Util.getBodyFromMap1(map);
//		pendexecuPresenter.main(body);
//
//		pendexecuPresenter.main1(body);
    }

//	@Override
//	protected void onResume() {
//
//		super.onResume();
//
//
//
//		Bitmap bmp = DaggerApplication.decodeImage(path);
//
//		drawable = new BitmapDrawable(bmp);
//		Registerimage.setBackground(drawable);
//	}
}

